<template>
  <div>
    <div class="node" v-has="{action: 'finance:invoice:list', effect: 'move'}">
      <div class="search_box topSelect">
        <SearchInput
          placeholder="手机号"
          label="手机号"
          style="margin-right:20px"
          :value="phone"
          :onChange="(val) => changeSearch('phone',val)"
          :onBlur="getQueryData"
        />
        <SearchInput
          placeholder="公司名字"
          label="公司名字"
          style="margin-right:20px"
          :value="companyName"
          :onChange="(val) => changeSearch('companyName',val)"
          :onBlur="getQueryData"
        />
        <div class="selectBox">
          <label>开票状态：</label>
          <el-select
            v-model="state"
            clearable
            @change="getQueryData()"
            placeholder="请选择"
          >
          <el-option label="申请中" :value="1"></el-option>
          <!-- <el-option label="微信订单" :value="2"></el-option> -->
          <el-option label="已开票" :value="3"></el-option>
          <el-option label="拒绝开票" :value="4"></el-option>
          <!-- <el-option label="个人充电桩订单" :value="5"></el-option> -->
          </el-select>
        </div>
        <div class="selectBox" style="margin-right:20px;display: flex;align-items: center;">
          <label>创建时间：</label>
          <el-date-picker
            v-model="appointmentTime"
            type="datetimerange"
            @change="changeTime"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            :picker-options="pickerOptions"
            style="height:40px"
          ></el-date-picker>
        </div>
        <div class="searchBox1" style="margin-left: 20px">
          <el-button  size="small" plain icon="el-icon-search" @click="getQueryData">查询</el-button>        
        </div>
      </div>
      <Panel title="发票管理">
        <div slot='ext' class="examine">
          <!-- <el-button type="success" icon="el-icon-folder-checked" @click="()=>editStore()">同意开票</el-button> -->
          <!-- <el-button  type="success" icon="el-icon-circle-check" @click="()=>finish()">开票完成</el-button> -->
          <form :action="url" method="POST" target="targetIfr">
            <input type="hidden" name="endTime" :value="endTime" id="">
            <input type="hidden" name="startTime" :value="startTime" id="">
            <input type="hidden" name="state" :value="state"  id="">
            <button  type="submit"  icon="el-icon-takeaway-box" class="export"><i class="el-icon-upload"></i>导出数据</button>
          </form>
        </div>
      <TableEncapsulation
        slot="body"
        :tableConfig="tableConfig"
        :tableData="tableData"
        rowId="uuid"
        @getCheckId="checkAll"
      >
      <template slot="operation" slot-scope="operation">
            <el-button size="mini" icon="el-icon-edit"
              v-if="operation.row.state==1"
              @click="()=>complate(operation.row)"
            >开票完成</el-button>
            <el-button size="mini" icon="el-icon-info"
              @click="()=>editStore(operation.row)"
            >发票详情</el-button>
            <!-- <el-button
              type="text"
              @click="()=>complate(operation.row)"
            >发票链接</el-button> -->
            <el-button size="mini" type="danger" icon="el-icon-delete"
              v-if="operation.row.state==1"
              @click="()=>remove(operation.row.uuid)"
            >开票失败</el-button>
          </template>
          <TablePager
            slot="pager"
            v-if="pager.use"
            :size="pager.size"
            :pageChange="pageChange"
            :show-total="pager.showTotal"
            :total="pager.total"
            :current="pager.current"
          >
            <span class="demonstration">GO></span>
          </TablePager>
      </TableEncapsulation>
      </Panel>
      <ModalPanel 
        :visible='showUrl'
        title="开票完成"
        :onCancel="onCancel"
        class="bannerDialog"
        :onOk="onSubmit">
        <div>
          <ModifyForm
            :hiddenBtn='true'
            :editColumn='editColumn'
            :updateData="updateData"
            labelWidth='100px'
            ref="configModal"
            class="ModifyForm"
            :temporaryData='modalData'>
          </ModifyForm>
        </div>
      </ModalPanel>

      <ModalPanel 
        :visible='showDetail'
        title="开票详情"
        :onCancel="onCancel1"
        class="bannerDialog"
        >
        <div>
          <div  slot="body">
        <el-form class="from_box" ref="form"  label-width="157px">
        <p class="h1" style="font-size:17px;font-weight:bold;padding: 8px 10px">基本信息</p>
        <div class="from_box">
          <el-form-item label="开票员：">{{modalData.clerk}}</el-form-item>
          <el-form-item label="发票代码  ：">{{modalData.invoiceCode}}</el-form-item>
          <el-form-item label="发票种类：">{{modalData.invoiceLine}}</el-form-item>
          <el-form-item label="发票号码：">{{modalData.invoiceNo}}</el-form-item>
          <el-form-item label="开票类型：">{{modalData.invoiceType==1? "蓝票": modalData.invoiceType==2? "红票" : '未知'}}</el-form-item>
          <el-form-item label="来源：">{{modalData.origin ===0 ? "app(微信)": modalData.origin===1 ?"新电途": '未知'}}</el-form-item>
          <el-form-item label="发票地址："><span v-if="modalData.pdfUrl"> {{modalData.pdfUrl}}<a style="margin-left:6px" target="_blank" :href="modalData.pdfUrl">下载</a> </span></el-form-item>
          <el-form-item label="用户手机号 ：">{{modalData.phone }}</el-form-item>
          <el-form-item label="开票总金额  ：">{{modalData.priceTotal}}</el-form-item>
           <el-form-item label="税率  ：">{{modalData.taxRate}}</el-form-item>
            <el-form-item label="开票总金额  ：">{{modalData.priceTotal}}</el-form-item>
          <!-- <el-form-item label="推送方式 ：">{{modalData.pushMode===-1?"不推送": modalData.pushMode===0?"邮箱": modalData.pushMode===1? "手机(默认)":modalData.pushMode===2? "手机、邮箱": "未知"  }}</el-form-item> -->
          <el-form-item label="抬头类型 ：">{{modalData.receiveType===1? "公司开票": "个人开票"}}</el-form-item>
          <el-form-item label="备注 ：">{{modalData.remark}}</el-form-item>
          <el-form-item label="开票方税号 ：">{{modalData.salerTaxNum}}</el-form-item>
          <el-form-item label="状态 ：">{{modalData.state===-1?"客户申请中(未处理)": modalData.state===2?"开票中": modalData.state===3? "已开票":modalData.state===4? "用户取消": modalData.state===5? "拒绝开票": modalData.state===6? "开票失败": "未知"}}</el-form-item>
          <el-form-item label="发票结果是否待推送 ：">{{modalData.waitNotify==1? "是": modalData.waitNotify==0? "否" : '未知'}}</el-form-item>
        </div>
      </el-form>
       <p class="h1" style="font-size:17px;font-weight:bold;padding: 8px 10px">开票订单</p>
    <TableEncapsulation
      :tableConfig="tableConfig1"
      :tableData="tableData1"
    >
        <TablePager
          slot="pager"
          v-if="pager1.use"
          :size="pager1.size"
          :pageChange="pageChange"
          :show-total="pager1.showTotal"
          :total="pager1.total"
          :current="pager1.current"
        >
          <span class="demonstration">GO></span>
        </TablePager>
    </TableEncapsulation>
      </div>
        </div>
      </ModalPanel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'finance:invoice:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import { objectFilter } from "@/tools/array";
import { dateFormat } from "@/tools/time";
export default {
  name: "financeInvoice",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModifyForm,
    ModalPanel
  },
  data() {
    return {
      url: this.$baseUrl+"/export/invoicing?token="+localStorage.getItem('user_token'),
      showUrl: false,
      companyName: '',
      phone: '',
      state: '',
      modalData:{},
      update: false,
      tableData: [],
      checkIds: [],
      query: {
        page: 1
      },
       pager: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      endTime: '',
      startTime: '',
      name: '',
      operation: true,
      appointmentTime: null,
      //-------------
      showDetail: false,
      tableData1: [],
      pager1: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      //-------------
      
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      editColumn: [
        {
          name: "链接",
          prop: "url",
          type: "text",
          required: true,
          width: 24
        },
      ],
    };
  },
  created() {
    let now = new Date().getTime() + 3600 * 1000 * 24
    let year = new Date(now).getFullYear()
    let month = new Date(now).getMonth() 
    let day = new Date(now).getDate()
    let last = new Date().getTime() - 3600 * 1000 * 24 * 30
    let lastYear =  new Date(last).getFullYear() 
    let LastMonth = new Date(last).getMonth() 
    let lastDay = new Date(last).getDate()
    this.appointmentTime = [ new Date(lastYear, LastMonth, lastDay, 0, 0,0), new Date(year, month, day, 0, 0,0)]
    this.endTime= this.appointmentTime ? (dateFormat(this.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : undefined
    this.startTime = this.appointmentTime ? (dateFormat(this.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : undefined
    this.getQueryData();
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "发票抬头/姓名",
            type: "text",
            prop: "companyName",
            align: "center"
          },
          {
            label: "税号",
            type: "text",
            prop: "dutyParagraph",
            align: "center"
          },
          
          {
            label: "邮箱",
            type: "text",
            prop: "email",
            align: "center"
          },
          {
            label: "手机号",
            type: "text",
            prop: "phone",
            align: "center"
          },
          {
            label: "来源",
            type: "other",
            prop: "origin",
            align: "center",
            fnc: val => val ===0 ? "app(微信)": val===1 ?"新电途": '未知',
            // class:val => val ? "defaluts" : "defaluts" 
          },
          {
            label: "总金额",
            type: "text",
            prop: "priceTotal",
            align: "center"
          },
          {
            label: "电费",
            type: "text",
            prop: "powerPrice",
            align: "center"
          },
          {
            label: "服务费",
            type: "text",
            prop: "serverPrice",
            align: "center"
          },
           {
            label: "类型",
            type: "other",
            prop: "dutyParagraph",
            align: "center",
            fnc: val => val ? '单位':"个人",
            class:val => val ? "defaluts" : "defaluts" 
          },
          {
            label: "状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 1 ? "申请中":  val == 2 ? '开票中':  val == 3 ? '已开票':val == 4 ? '用户取消':val == 5 ? '拒绝开票':val == 6 ? '开票失败':"未知错误",
            class:val => val == 1 ? "wait" : val == 2 ? "sheng2": val == 3 ? "agree" :  val == 4 ? "cancel" :"cancel" 
          },
          {
            label: "开户行",
            type: "text",
            prop: "bankName",
            align: "center"
          },
          {
            label: "卡号",
            type: "text",
            prop: "accountNumber",
            align: "center"
          },
          {
            label: "地址",
            type: "address",
            prop: "text",
            align: "center"
          },
          {
            label: "链接",
            type: "url",
            prop: "pdfUrl",
            align: "center",
            overflow: true
          },
          {
            label: "创建时间",
            type: "text",
            prop: "createTime",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    },
    tableConfig1 () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "订单号",
            type: "text",
            prop: "oid",
            align: "center"
          },
          {
            label: "电费",
            type: "text",
            prop: "powerPrice",
            align: "center"
          },
          {
            label: "服务费",
            type: "text",
            prop: "serverPrice",
            align: "center"
          },
          {
            label: "附加费",
            type: "text",
            prop: "surcharge",
            align: "center"
          },
          {
            label: "总金额",
            type: "text",
            prop: "priceTotal",
            align: "center"
          },
          {
            label: "时间",
            type: "text",
            prop: "createTime",
            align: "center"
          },
          // this.operation && {
          //   type: "operation",
          //   align: "center",
          //   label: "操作",
          //   width:180
          // }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    checkAll(data){
      this.checkIds = data
    },
    async finish() {
      const res = await request({
        url: "/invoicing/complete",
        method: "POST",
        data: this.checkIds
      });
     if(res.code ==0){
       this.checkIds = []
       this.getQueryData()
       this.$message.success('操作成功')
     }
    },
    changeTime(){
      this.endTime = this.appointmentTime ? (dateFormat(this.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : undefined
      this.startTime = this.appointmentTime ? (dateFormat(this.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : undefined
      this.getQueryData()
    },
    async getQueryData() {
      let endTime = this.endTime
      let startTime = this.startTime
      let companyName = this.companyName
      let phone =this.phone
      let state = this.state
      let page = this.pager.current
      let search = objectFilter({startTime, endTime, state, companyName, page, phone})
      const res = await request({
        url: "/invoicing/list",
        method: "POST",
        data: search
      });
      // res.page.list.map(item => {
      //   item.total = (item.priceTotal + item.powerPrice).toFixed(2)
      //   return item
      // })
      this.tableData = res.page.list
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getQueryData();
    },
    changeSearch(key, val) {
      this[key] = val;
      this.pager.current = 1;
    },
    //----------------------------
    editStore(row){
      this.modalData = row
      this.showDetail = true
      this.getQueryDataOrder(row.uuid)
    },
    onCancel1(){
      this.showDetail = false
    },
    async getQueryDataOrder(uuid) {
      let page = this.pager1.current
      const res = await request({
        url: `/invoicing/info`,
        method: "POST",
        data: {UUID: uuid, page}
      });
      this.tableData1 = res.page.list
      this.pager1.total = res.page.totalCount
      this.pager1.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getQueryData();
    },
    ///----------------------------
    commentDetail(id){
      this.$router.push({ path: "/storeDetail",query:{id:id,type: "toview"} })
    },
    complate(row){
      this.modalData = row
      if(row.url){
        this.update = true
      }else{
        this.update = false
      }
      this.showUrl = true
    },
     onCancel(){
      this.showUrl = false
    },
    async updateData(values){
      let urls, msg
      const { uuid, url } = values
      urls =this.update ? '/invoicing/update/url' : '/invoicing/add/url'
      let res = await request({
        url: urls,
        method: 'POST',
        data: { uuid, url }
      })
      if (res.code !==0) return
      this.$message.success('操作成功')
      this.showUrl = false
      this.getQueryData()
    },
    async agree(id){
      let res = await request({
        url: `/invoicing/agree/${id}`,
        method: "POST",
        // data: [id]
        })
        if(res.code ==0)
        this.$message.success('操作成功')
        if(this.tableData.length===1 && this.pager.current>1)
        this.$set(this.pager,'current', this.pager.current-1)
        this.getQueryData()
    },
    onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    remove(id){
       this.$confirm('确认拒绝开票吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        let res = await request({
        url: "/invoicing/refuse",
        method: "POST",
        data: [id]
        })
        if(res.code ==0)
        this.$message.success('操作成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getQueryData()
      })
    },
  }
}
</script>
<style lang='scss' scope>
.export {
    color: #FFF;
    background-color: #F56C6C;
    border-color: #F56C6C;
    border: 1px solid #F56C6C;
    border-radius: 5px;
    padding: 8px 10px;
    margin: 0 20px;
}
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.from_box{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.el-form-item{
  width: 45%;
      background: #eef2f5;
      padding-left: 10px;
}
.el-form-item__label{
  text-align: left;
}
</style>